/**
 * 
 */
package org.istt.web;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.istt.domain.Report;
import org.istt.service.ReportManager;
import org.istt.web.helper.ExtendedPaginatedList;
import org.istt.web.helper.PaginateListFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;

/**
 * @author Ndtho
 *
 */
public class ReportAction extends BaseAction<ReportManager, Report, Long> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File uploadFile;
	
	private String uploadFileContentType;
	
	private String uploadFileFileName;
	protected PaginateListFactory paginateListFactory;
	
	private String reportName;
	private String description;
	private String functionName;
	private String cancel;
	public String getCancel() {
		return cancel;
	}

	public void setCancel(String cancel) {
		this.cancel = cancel;
	}


	private String delete;
	public String getDelete() {
		return delete;
	}

	public void setDelete(String delete) {
		this.delete = delete;
	}
	
	@Override
	public String save() {
		
        if (log.isDebugEnabled()) {
            log.debug("entering 'save' method");
        }
        if(StringUtils.isNotEmpty(uploadFileFileName)){
        	uploadFileFileName = new StringBuilder(new SimpleDateFormat("yyMMddHHmm").format(new Date())).toString() + "_"+ uploadFileFileName ;
            
            entity = getEntity();
            entity.setFunctionName(uploadFileFileName);
            
            // Xoa file truoc khi thay the bang file tmp khac
            removeTmpFile(functionName);
            
    		String uploadDir = getDocumentLocation() + uploadFileFileName;
    		
            // Create the directory if it doesn't exist
            File dirPath = new File(uploadDir);

            try {
    			FileUtils.copyFile(uploadFile, dirPath);
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }else{
        	// Update lai ten file cu
        	if(StringUtils.isNotEmpty(functionName)){
        		entity = getEntity();
                entity.setFunctionName(functionName);
        	}
        }
		
		mgr.save(entity);
    	setSaveMessage();// addition or edit message ??
    	
        ActionContext.getContext().getSession().put("message", getText(getSavedMessage()));
        
        return SUCCESS;
    }
	
	private void removeTmpFile(String fileName){
		File selectedFile = new File(getDocumentLocation()+fileName);
		log.debug(">>>>>>>>>>>Filename: "+getDocumentLocation()+fileName);
		try {
			selectedFile.delete();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public boolean isFileValid() {
		if(StringUtils.isNotEmpty(uploadFileFileName)){
			return true;
		}else{
			if(StringUtils.isNotEmpty(functionName)){
				return true;
			}else{
				return false;
			}
		}
	}
	
	public String search() {
		if (log.isDebugEnabled()) {
			log.debug("entering 'search attachFile' method");
		}
		ExtendedPaginatedList paginatedList = paginateListFactory.getPaginatedListFromRequest(ServletActionContext.getRequest());
		reportList = ((ReportManager)this.mgr).searchReport(reportName, paginatedList);
		
		return SUCCESS;
	}

	private ExtendedPaginatedList reportList;
	
	@Override
	public String execute() {
		if (cancel != null) {
            return "cancel";
        }
        
        if (delete != null) {
            return "delete";
        }
        
        return SUCCESS;
    }
	
	@Override
	public Report getEntity() {
		Report tmpReport = new Report();
		
		tmpReport.setId(getId());
		tmpReport.setDescription(description);
		tmpReport.setReportName(reportName);
		tmpReport.setFunctionName(functionName);
		
		return tmpReport;
	}

	
	@Override
	public Long getId() {
		// TODO Auto-generated method stub
		if(entity!=null) return entity.getId();
		
		return id;
	}
	
	
	public ExtendedPaginatedList getReportList() {
		return reportList;
	}


	@Override
	public String list(){
		ExtendedPaginatedList paginatedList = paginateListFactory.getPaginatedListFromRequest(ServletActionContext.getRequest());
		
		reportList = ((ReportManager)this.mgr).getReportList(paginatedList);
		return SUCCESS;
	}
	
	public String remove(){
		String strFileName = "";
		if(entity!=null) strFileName = entity.getFunctionName();
		
		String result = delete();
		
		// Delete template file
		if(StringUtils.isNotEmpty(result)){
			removeTmpFile(strFileName);
		}
		return result;
	}

	@Autowired
    public void setPaginateListFactory(PaginateListFactory paginateListFactory) {
        this.paginateListFactory = paginateListFactory;
    }

	public void setReportList(ExtendedPaginatedList reportList) {
		this.reportList = reportList;
	}


	public void setReportName(String reportName) {
		this.reportName = reportName;
	}


	public String getReportName() {
		if(entity!=null){
			this.reportName = entity.getReportName();
		}
		return this.reportName;
	}


	public void setDescription(String description) {
		this.description = description;
	}


	public String getDescription() {
		if(entity!=null){
			this.description = entity.getDescription();
		}
		return this.description;
	}
	@Override
	protected void setSaveMessage() {
        ActionContext.getContext().getSession().put("message", 
                getText("category.saved"));
	}

	@Override
	protected void setDeleteMessage() {
        ActionContext.getContext().getSession().put("message", 
                getText("category.deleted"));
	}

	public boolean isAllowDelete(){
		log.debug("Enter method isAllowDelete!");
		boolean isValid = true;
		entity = getEntity();
		if(entity.getCategories().size()!=0) return false;
		return isValid;
	}

	public void setFunctionName(String functionName) {
		this.functionName = functionName;
	}

	public String getFunctionName() {
		if(entity!=null){
			this.functionName = entity.getFunctionName();
		}
		return functionName;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}

	public String getUploadFileContentType() {
		return uploadFileContentType;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}
}
